<template>
  <div class="login-container">
    <div class="login-box">
      <div style="padding:20px;background-color: white;margin-left: 100px;border-radius: 25px;box-shadow: 0 0 10px rgba(0,0,0,0.2)">
        <el-form ref="formRef" :rules="data.rules" :model="data.form"  style="width: 350px">
          <div style="margin-bottom: 30px;font-size: 24px;color: #0742b1;font-weight: bold; text-align:center" >欢迎登录租宿管理系统</div>
          <el-form-item prop="username">
            <el-input size="large" v-model="data.form.username" placeholder="请输入账号" prefix-icon="User"></el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input show-password size="large" v-model="data.form.password" placeholder="请输入密码" prefix-icon="Lock"></el-input>
          </el-form-item>

          <el-form-item prop="role">
            <el-select v-model="data.form.role" style="width: 100%;" size="large">
              <el-option label="用户" value="user"></el-option>
              <el-option label="管理员" value="admin"></el-option>
              <el-option label="房东" value="owner"></el-option>
            </el-select>
          </el-form-item>

          <div>
            <el-button size="large" style="width: 100%" type="primary" @click="login">登录</el-button>
          </div>
          <div style="text-align:right">还没有账号？请
            <a style="color: #0742b1;text-decoration: none" href="/register">注册</a>
          </div>



        </el-form>
      </div>

    </div>
  </div>
</template>

<script setup>

import { reactive ,ref} from "vue";
import {ElMessage} from "element-plus"
import {User,Lock} from "@element-plus/icons-vue"
import request from "../utils/request";
import {useTokenStore} from "../stores/token.js"
const tokenStore = useTokenStore()
// import {useWebSocketStore} from "../stores/webSocket.js";
// 新增路由相关导入
import { useRouter } from 'vue-router'
const router = useRouter() // 初始化路由实例
// const websocketStore = useWebSocketStore();

const data = reactive({
   form:{
     role:'user',
   },
   rules:{
      username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur' }
      ]
  }
})

const formRef = ref()

const login = () => {
  formRef.value.validate((valid) => {
    if (valid){
      request.post('web/login',data.form).then(res => {

        if (res.code === '200'){
          console.log(res.data)
          //登录成功
          ElMessage.success('登录成功')

          //存储token
          localStorage.setItem('token',JSON.stringify(res.data.token))
          tokenStore.setToken(res.data.token)
          console.log("tokenStore的token："+tokenStore.token);

          //存储后台返回的用户数据信息
          localStorage.setItem('localStorageUser',JSON.stringify(res.data.account))//把json对象转换成json字符串存储

          // 获取用户信息
          const user = JSON.parse(localStorage.getItem('localStorageUser'));
          // 使用 Pinia 初始化 WebSocket

          // websocketStore.initWebSocket(user.name); // 传入用户名

          setTimeout(() => {
            const roleMap = {
              user: '/front_page/home',
              admin: '/admin_manager/home',
              owner: '/owner_manager/home'
            };
            router.push(roleMap[data.form.role])
                .catch(err => {
                  console.error('路由跳转失败:', err);
                  ElMessage.error('页面跳转异常，请检查路由配置');
                });
          }, 500);


        }else {
          ElMessage.error(res.msg)
        }
      })
    }

})
}


</script>

<style scoped>
  .login-container {
    height: 100vh;
    overflow: hidden;
    background-image: url("https://house1205.oss-cn-shenzhen.aliyuncs.com/%E5%89%8D%E7%AB%AF%E8%83%8C%E6%99%AF.png");
    background-size: 100% 100%;
  }
  .login-box{
    width: 50%;
    height: 100%;
    display: flex;
    align-items: center;
    right: 0;
    position: absolute;
  }
</style>